const request = require('request');
var fs = require("fs");

var accessTokenJson = require("./access_token");
const wxConfig = appRequire('config');

// 导出对象，供其它模块调用
module.exports = {
    getAccessToken
};


async function getAccessToken(req, response) {
    let postData = req.body
    let appid = wxConfig['wxMini' + postData.source].appId
    let appsecret = wxConfig['wxMini' + postData.source].secret
    return new Promise(function (resolve, reject) {
        var currentTime = new Date().getTime();
        if (accessTokenJson.access_token === "" || accessTokenJson.expires_time < currentTime) {
            request.get(
                `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
                (err, httpResponse, body) => {
                    var result = JSON.parse(body);
                    accessTokenJson.access_token = result.access_token;
                    accessTokenJson.expires_time = new Date().getTime() + (parseInt(result.expires_in) - 3600) * 1000;
                    //更新本地存储的
                    fs.writeFile('./controllers/wx/access_token.json', JSON.stringify(accessTokenJson), err => {
                        resolve(result.access_token);
                    });
                }
            )
        } else {
            //将本地存储的 access_token 返回
            resolve(accessTokenJson.access_token);
        }
    })
}